package com.jz.banner.screen.net.observer

import android.app.Activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import com.jz.banner.screen.R
import com.jz.banner.screen.bean.BaseBean
import com.jz.banner.screen.ui.activity.LoginActivity
import io.reactivex.Observer
import io.reactivex.disposables.Disposable

/**
 * 创建者     Noel
 * 创建时间   2018/1/20 16:55
 * 描述	       对Observer 根据后台返回的状态封装。
 */


abstract class BaseObserver<T>(
    protected var activity: Activity
) : Observer<BaseBean<out T>> {
    protected var mDisposable: Disposable? = null

    override fun onNext(t: BaseBean<out T>) {
        when (t.code) {
            1 -> { //请求成功
                if (t.data != null) {
                    onSuccessNext(t)
                } else {
                    dataIsNull(t)
                }
            }
            -1 -> { //Token已过期或注销
                //TODO:调用弹出对话框，退出app
                /*if (!App.isShowLogoutDialog) {
                    App.isShowLogoutDialog = true*/
                showLogoutDialog(activity, t.message)
                /* }*/
                onError(IllegalStateException(t.message))/*"Token已过期或注销。" +*/
            }
            else -> { //0失败，或者其他原因
                onError(IllegalStateException(t.message))
            }
        }
    }


    /*请求数据基类返的data为空*/
    protected open fun dataIsNull(t: BaseBean<out T>) {
        if (!isHandleRequestMultiData()) mDisposable!!.dispose()
    }

    protected abstract fun onSuccessNext(t: BaseBean<out T>)

    private fun showLogoutDialog(acty: Activity, msg: String?) {
        AlertDialog.Builder(acty)
            .setMessage(/*String.format(acty.getString(R.string.login_expired), msg)*/msg)
            .setCancelable(false)
            .setPositiveButton(R.string.confirm) { dialog, _ -> goBackLoginActivity(acty, dialog) }
            .create()
            .show()
    }

    /*返回登录页面*/
    fun goBackLoginActivity(acty: Activity, dialog: DialogInterface) {
        dialog.dismiss()
        //TODO:退出到登陆
        var intent = Intent(acty, LoginActivity::class.java)
        acty.startActivity(intent)
        acty.finish()
        acty.overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_bottom)
    }

    /*开启处理异步请求多个数据，同步处理。例如：false之后，一旦其中一个请求失败或者为空，则取消剩余的请求*/
    protected open fun isHandleRequestMultiData(): Boolean = false
}
